package org.example.thread.testSync;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author liyishan
 * @date 2025/4/3
 * @description
 */
public class TestCompletionService {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        CompletionService executorCompletionService = new ExecutorCompletionService<>(executorService);
        List<String> products = new ArrayList<>();
        products.add("product1");
        products.add("product2");
        products.add("product3");

        for (String product : products) {
            executorCompletionService.submit(() -> {
                // 模拟查询商品价格的逻辑，这里使用随机数模拟价格
                System.out.println("Fetching price for product: " + product);
                double price = Math.random() * 100;
                Thread.sleep((long)(Math.random() * 1000)); // 模拟查询时间
                return price;
            });
        }

        for (int i = 0; i < products.size(); i++) {
            try {
                Future<Double> result = executorCompletionService.take();
                Double price = result.get();
                System.out.println("Product " + products.get(i) + " price: $" + price);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭ExecutorService
        executorService.shutdown();

    }
}
